package com.xm.rsi.utils;

import com.xm.rsi.common.ErrorCode;
import com.xm.rsi.exception.BusinessException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TifToJpg {
    public static String getJpgUrl(InputStream inputStream) {
        try {
            int available = inputStream.available();
            
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            Future<BufferedImage> readFuture = executorService.submit(() -> ImageIO.read(inputStream));
            Future<BufferedImage> compressFuture = executorService.submit(() -> {
                BufferedImage tifImage = readFuture.get();
                return compressImage(tifImage);
            });
            Future<byte[]> writeFuture = executorService.submit(() -> {
                BufferedImage compressedImage = compressFuture.get();
                ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream(available);
                ImageIO.write(compressedImage, "png", jpgOutputStream);
                return jpgOutputStream.toByteArray();
            });
            byte[] jpgData = writeFuture.get();

//            long start = System.currentTimeMillis();
//            BufferedImage tifImage = ImageIO.read(inputStream);
//            BufferedImage compressedImage = compressImage(tifImage);
//            ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream(available);
//            ImageIO.write(compressedImage, "png", jpgOutputStream);
//            byte[] jpgData = jpgOutputStream.toByteArray();
//            long end = System.currentTimeMillis();
//            System.out.println(end - start);
            
            // 将jpgData转换为Base64编码的字符串
            String base64Image = Base64.getEncoder().encodeToString(jpgData);

            // 构建HTML图像元素的src属性
            return "data:image/jpeg;base64," + base64Image;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "转载图片异常");
        }
    }

    private static BufferedImage compressImage(BufferedImage image) {
        Image scaledImage = image.getScaledInstance((int) (image.getWidth() * 0.1), (int) (image.getHeight() * 0.1), Image.SCALE_SMOOTH);
        BufferedImage bufferedImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(scaledImage, 0, 0, null);
        return bufferedImage;
    }
}
